import { Prefab, Node, NodePool, instantiate } from 'cc';
import BaseSingleClass from "../base/BaseSingleClass";
import PrefabHelper from './PrefabHelper';

export default class PoolHelper extends BaseSingleClass{
    /** prefab实例化的node */
    private poolMap=new Map<Prefab,NodePool>()
    /** 所有prefab */
    //private prefabMap:Map<string,Prefab>=new Map<string,Prefab>()
    /**
     * 回收节点
     * @param prefab 预制体
     * @param node 
     */
    put(prefab:Prefab,node:Node):void{
        const pool=this.getPool(prefab)
        pool.put(node)
    }
    /**
     * 回收节点
     * @param name prefab名字
     * @param node 
     */
    putNode(name:string,node:Node):void{
        PrefabHelper.getInstance().getPrefabAsync(name).then(prefab=>{
            this.put(prefab,node)
        }).catch(err=>{
            console.error(err)
        })
        /*const map=this.prefabMap
        const prefab=map.get(name)
        this.put(prefab,node)*/
    }
    /*setPrefab(prefab:Prefab):void{
        this.prefabMap.set(prefab.name,prefab)
    }*/
    get(prefab:Prefab):Node{
        const pool=this.getPool(prefab)
        let node:Node
        if(pool.size()>0){
            node=pool.get()
        }else{
            node=instantiate(prefab)
        }
        return node
    }
    getNode(name:string):Promise<Node>{
        return new Promise<Node>((resolve,reject)=>{
            PrefabHelper.getInstance().getPrefabAsync(name).then(prefab=>{
                if(!prefab){
                    console.error("prefab is null",name)
                    reject("prefab is null")
                }
                resolve(this.get(prefab))
            }).catch(err=>{
                reject(err)
            })
        })
        /*
        //const map=this.prefabMap
        const prefab=PrefabHelper.getInstance().getPrefab(name)//map.get(name)
        if(!prefab){
            console.error("prefab is null",name)
            return null
        }
        return this.get(prefab)*/
    }
    getPool(prefab:Prefab):NodePool{
        let pool=this.poolMap.get(prefab)
        if(!pool){
            pool=new NodePool()
            this.poolMap.set(prefab,pool)
        }
        return pool
    }
}